<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type");

// 读取用户数据
$userDataDir = 'data/users.json';
$userData = json_decode(file_get_contents($userDataDir), true);

// 接收 POST 请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 处理登录
    if (isset($_POST['username']) && isset($_POST['password'])) {
        $username = $_POST['username'];
        $password = $_POST['password'];

        // 检查用户名和密码
        if (checkCredentials($userData, $username, $password)) {
            echo json_encode(array('status' => 200, 'message' => 'Login successful.'));
        } else {
            echo json_encode(array('status' => 500, 'message' => 'Invalid username or password.'));
        }
    } else {
        echo json_encode(array('status' => 500, 'message' => 'Invalid data.'));
    }
}

// 检查用户名和密码
function checkCredentials($userData, $username, $password)
{
    foreach ($userData['users'] as $user) {
        if ($user['username'] === $username && password_verify($password, $user['password'])) {
            return true;
        }
    }
    return false;
}
?>